<?php

namespace app\common\model;

use app\common\lib\Show;
use app\common\lib\Status;
use Htlove\Time;
use think\Exception;
use think\facade\Log;

class CouponCoupon extends Base
{

    protected $deleteTime = "delete_time";

    /**
     * @param string $openid
     * @return array|void
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCouponByUserList(string $openid = '')
    {
        //查询所有可用优惠券
        $time = time();
        try {
            $row = $this->where('start_time', "<", $time)
                ->where('end_time', '>', $time)
                ->where('push', 1)
                ->select()
                ->toArray();
        } catch (\Exception $e) {
            throw new Exception("查询失败");
        }
        if (empty($row)) {
            return [];
        }
        $lists = [];
        foreach ($row as $k => $v) {
            $lists[$k] = $v;
            //查询 是否自己已经领取了
            if ($v['new_limit'] != 0) { //限制新用户领取
                $count = (new CouponReceive())->getUserCouponReceiveByCount($openid);
                if ($count['count'] != 0) {
                    $lists[$k]['is_l'] = 0;
                    continue;
                }
            }
            //没有限制新用户领取
            if ($v['receive_limit'] != 0) {  //总数超过
                $count = (new CouponReceive())->getUserCouponReceiveIdByCount([
                    ['coupon_id','=',$v['id']],
                    ["openid", '=', $openid],
                ],'count(*) as count');
                if ($count['count'] >= $v['receive_limit']) {
                    $lists[$k]['is_l'] = 0;
                    continue;
                }
            }
            //每天领取
            $count = (new CouponReceive())->getUserCouponReceiveIdByCount([
                ['coupon_id','=',$v['id']],
                ["openid", '=', $openid],
                ['create_time', 'between', Time::instance()->today()]
            ],'count(*) as count');
            if ($count['count'] >= $v['receive_day_limit']) {
                $lists[$k]['is_l'] = 0;
                continue;
            }
            $lists[$k]['is_l'] = 1;
        }
        return $lists;

    }
}